const app = getApp()
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  properties: {
    count: String, //父子传参
    className: String,
    modelName: String,
    cropper: Boolean
  },
  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
    count: 1, //限制图片数量
    ishide: false,
    picslist: [],
    imgUrl: app.globalData.imgUrl,
    originImgs: [],
    datalist: [],
    hosts: wx.getStorageSync('uploadUrl'),
    fileName: "",
    cropper: false
  },
  // 上传图片
  methods: {
    chooseImg: function(e) {
      var that = this;
      var imgs = this.data.imgs;
      if (imgs.length >= 9) {
        this.setData({
          lenMore: 1
        });
        setTimeout(function() {
          that.setData({
            lenMore: 0
          });
        }, 2500);
        return false;
      }
      wx.chooseImage({
        count: that.data.count - (that.data.datalist.length || 0),
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths;
          var imgs = that.data.imgs;
          
          for (var i = 0; i < tempFilePaths.length; i++) {
            if (imgs.length > that.data.count - 1) {
              that.setData({
                imgs: imgs
              });
              return false;
            } else {
              var item = {
                imgPath: tempFilePaths[i],
                cropper: true
              }
              imgs.push(item);
              if (that.data.datalist.length) {
                if (that.data.datalist.length > that.data.count - 1) {
                  that.setData({
                    ishide: true
                  });
                }
              } else {
                if (that.data.imgs.length > that.data.count - 1) {
                  that.setData({
                    ishide: true
                  });
                }
              }
            }
          }

          that.setData({imgs});
          
          if (!that.data.cropper){
            that.uploadFile(imgs);  
          } 

          that.triggerEvent("chooseImg"); //触发回调
        }
      });
    },
    // 删除图片
    deleteImg: function(e) {
      var imgs = this.data.imgs;
      var picslist = this.data.picslist;
      var index = e.currentTarget.dataset.index;
      imgs.splice(index, 1);
      picslist.splice(index, 1);
      this.setData({
        imgs: imgs,
        picslist: picslist
      });
      this.datalist();
      this.triggerEvent("deleteImg"); //触发回调
    },

    // 删除原来图片
    deloriginImg: function(e) {
      var originImgs = this.data.originImgs;
      var index = e.currentTarget.dataset.index;
      originImgs.splice(index, 1);
      this.setData({
        originImgs: originImgs,
      });
      this.datalist();

      this.triggerEvent("deloriginImg"); //触发回调
    },

    // 预览图片
    previewImg: function(e) {
      //获取当前图片的下标
      var index = e.currentTarget.dataset.index;

      //所有图片
      var imgs = this.data.datalist.map(item => {
        return this.data.hosts + item.imgPath
      });
      wx.previewImage({
        //当前显示图片
        current: imgs[index],
        //所有图片
        urls: imgs
      })
    },

    datalist: function() {
      var imglist = []
      if (this.data.picslist.length > 0 && this.data.originImgs.length > 0) {
        var imglist = this.data.originImgs.concat(this.data.picslist)
      } else if (this.data.picslist.length > 0 && this.data.originImgs.length < 1) {
        var imglist = this.data.picslist
      } else {
        var imglist = this.data.originImgs
      }

      this.setData({
        datalist: imglist
      })
      if (this.data.datalist.length < Number(this.data.count) - 1) {
        this.setData({
          ishide: false
        });
      }
    },





    //获取裁剪图片
    getCropperImg(e) {
      var that = this;
      var imgs = this.data.imgs
      imgs.map((item, index) => {
        if (index == e.detail.index) {
          item.cropper = false
        }
      })
      this.setData({ imgs})
      that.cropperUploadFile(e.detail.url);
    },


    cropperUploadFile: function(pics) {
      var that = this;
      that.setData({
        picslist: [],
        loading: true
      })
      wx.uploadFile({
        url: app.globalData.apiUrl + "/" + that.data.modelName + '/protected/comm/file/' + that.data.className + '/fileUpload',
        header: {
          "Authorization": wx.getStorageSync('Authorization'),
        },
        formData: {
          width: 750
        },
        filePath: pics,
        name: 'file',
        success: function(res) {
          if (typeof res.data == "string") {
            var resdata = JSON.parse(res.data)
          }
          if (resdata.success) {
            var picObj = {
              imgName: resdata.datas.vo.fileName,
              imgPath: resdata.datas.vo.relativeFilePath
            }
            var picdata = that.data.picslist.concat(picObj);
            console.log('picdata:', picdata)
            that.setData({
              picslist: picdata,
              loading: false
            })
            that.datalist();
          }
        },
        fail: function(res) {
          wx.showToast({
            icon: 'none',
            title: '图片上传失败',
          })
        }

      })
    },




    //上传图片
    uploadFile: function (pics) {
      var that = this;
      that.setData({
        picslist: [],
        loading:true
      })      
      for (var i = 0; i < pics.length; i++) {
        wx.uploadFile({
          url: app.globalData.apiUrl +"/"+ that.data.modelName+'/protected/comm/file/' + that.data.className +'/fileUpload',
          header: {
            "Authorization": wx.getStorageSync('Authorization'),
          },
          formData: { 
            width:750
            },
          filePath: pics[i].imgPath,
          name: 'file',
          success: function (res) {    
            if (typeof res.data =="string"){
              var resdata = JSON.parse(res.data)
              }    
            if (resdata.success) { 
              var picObj={
                imgName: resdata.datas.vo.fileName,
                imgPath: resdata.datas.vo.relativeFilePath
              }
              var picdata = that.data.picslist.concat(picObj);
              console.log('picdata:',picdata)
              that.setData({
                picslist: picdata, 
                loading:false
              }) 
              that.datalist();         
            }  
          },
          fail: function (res) {
            wx.showToast({
              icon: 'none',
              title: '图片上传失败',
            })
          }

        })
      }
    },
  },


})